package com.mycompany;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.sf.jasperreports.engine.JRException;

import org.apache.wicket.RequestCycle;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.DownloadLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.ListDataProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.protocol.http.WicketURLEncoder;
import org.apache.wicket.request.target.resource.ResourceStreamRequestTarget;
import org.apache.wicket.util.resource.FileResourceStream;
import org.apache.wicket.util.resource.IResourceStream;

import ar.com.fdvs.dj.domain.builders.ColumnBuilderException;

import com.db.DictionaryDB;

public class MainPage extends WebPage {

	final Form form = new Form("form");

	final List<String[]> wordList = new ArrayList<String[]>();

	private static String choiceMade;

	final DropDownChoice languageFromDropDown;

	final DropDownChoice languageToDropDown;

	ListView translationList;

	final TextField<String> wordSearch = new TextField<String>("wordSearch", new Model());

	String addTranslations = "";

 

	public static String getChoiceMade() {
		return choiceMade;
	}

	public void setChoiceMade(String choiceMade) {
		this.choiceMade = choiceMade;
	}

	public MainPage() {

		 
		// Form containing all the components
		add(form);

		form.add(wordSearch);
		
		DictionaryDB.getInstance().connect();
 

		ArrayList languagesFromList = new ArrayList();

		languagesFromList.add("English");

		ArrayList languagesToList = new ArrayList();
		languagesToList.add("Castellano");
		languagesToList.add("Magyar");
	 
		
		//Begin : Drop Down select 
		
		languageFromDropDown = new DropDownChoice("languageFrom",
				new Model<String>(), languagesFromList) {

			protected boolean wantOnSelectionChangedNotifications() {
				return true;
			}

			protected void onSelectionChanged(final Object newSelection) {

				MainPage.this.setChoiceMade((String) newSelection);
			}

		};

		form.add(languageFromDropDown);

		languageToDropDown = new DropDownChoice("languageTo",
				new Model<String>(), languagesToList) {

			protected boolean wantOnSelectionChangedNotifications() {
				return true;
			}

			protected void onSelectionChanged(final Object newSelection) {

				MainPage.this.setChoiceMade((String) newSelection);
			}

		};

		form.add(languageToDropDown);

		//End : Drop Down select 
		

		final Button addToListButton = new Button("addToListButton") {

			@Override
			public void onSubmit() {

				List<String> choicesFrom = languageFromDropDown.getChoices();
				List<String> choicesTo = languageToDropDown.getChoices();

				String from = choicesFrom.get(Integer
						.valueOf(languageFromDropDown.getInput()));
				String to = choicesTo.get(Integer.valueOf(languageToDropDown
						.getInput()));

				boolean addNewRow = true;

				String[] newRow = { from, to, wordSearch.getValue(),
						addTranslations };
				for (int z = 0; z < wordList.size(); z++) {
					if (wordList.get(z)[0].equals(from)) {
						if (wordList.get(z)[1].equals(to)) {
							if (wordList.get(z)[2]
									.equals(wordSearch.getValue())) {
								addNewRow = false;
								break;
							}
						}
					}

				}

				if (addNewRow) {
					wordList.add(newRow);
				}

				this.setEnabled(false);

			}

		};

		addToListButton.setEnabled(false);

		form.add(addToListButton);

		List listOfTranslations = Arrays.asList(new String[] {});
		translationList = new ListView("translationList", listOfTranslations) {
			protected void populateItem(ListItem item) {
				item.add(new Label("translationLabel", item.getModel()));
			}
		};
		form.add(translationList);

 		
		final DataView<String[]> dataView = new DataView<String[]>("simple",
				new ListDataProvider<String[]>(wordList)) {

			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(Item<String[]> item) {

				String[] row = item.getModelObject();
				item.add(new Label("from", row[0]));
				item.add(new Label("word", row[1]));
				item.add(new Label("to", row[2]));
				item.add(new Label("translation", row[3]));
				item.add(new ActionPanel("rowRemoval", item.getModel()));
			}

		};

		form.add(dataView);

		Button translateWordButton = new Button("translateWordButton") {
			public void onSubmit() {
						
				List<String> choicesFrom = languageFromDropDown.getChoices();
				List<String> choicesTo = languageToDropDown.getChoices();
				
				if (!languageFromDropDown.getInput().isEmpty()
						&& !languageToDropDown.getInput().isEmpty()) {
					String from = choicesFrom.get(Integer
							.valueOf(languageFromDropDown.getInput()));
					String to = choicesTo.get(Integer
							.valueOf(languageToDropDown.getInput()));

					 
					
					if (!wordSearch.getValue().equals("")) {
						
					
						ArrayList<String> results = DictionaryDB.getInstance()
								.queryWordTranslation(wordSearch.getValue(),
										from, to);
					 
						translationList.getModel().setObject(results);
					
						if (results.size() == 1
								&& (results.get(0).equals("Word not found") 
									|| results.get(0).equals("Translation not found")) ) {
							addToListButton.setEnabled(false);
						}

						else {
							boolean addNewRow = true;

							String[] newRow = { from, to,
									wordSearch.getValue(), addTranslations };
							for (int z = 0; z < wordList.size(); z++) {
								if (wordList.get(z)[0].equals(from)) {
									if (wordList.get(z)[1].equals(to)) {
										if (wordList.get(z)[2]
												.equals(wordSearch.getValue())) {
											addNewRow = false;
											break;
										}
									}
								}
							}

							if (addNewRow) {
								addToListButton.setEnabled(true);
								addTranslations = "";
								int j = 0;
								for (; j < results.size() - 1; j++) {
									addTranslations = addTranslations
											.concat(results.get(j) + ", ");

								}

								addTranslations = addTranslations
										.concat(results.get(j));
							}

							else {
								addToListButton.setEnabled(false);
							}

						}
					}

					else {
						addToListButton.setEnabled(false);
					}
				}

			}
		};
		
		

		form.add(translateWordButton);
	
		ExportDownloadLink wordListPdfDownloadLink = new ExportDownloadLink("wordListPdfExport", new File(""));
		form.add(wordListPdfDownloadLink);
		
	}

	private class ActionPanel extends Panel {
	 
		public ActionPanel(String id, final IModel<String[]> model) {
			super(id, model);

			SubmitLink removeLink = new SubmitLink("remove", form) {
				@Override
				public void onSubmit() {
					String[] row = ((String[]) model.getObject());

					for (int k = 0; k < wordList.size(); k++) {
						String[] temp = wordList.get(k);
						if (temp[0] == row[0])
							if (temp[1] == row[1])
								if (temp[2] == row[2])
									wordList.remove(k);
					}

				}
			};
			removeLink.setDefaultFormProcessing(false);
			add(removeLink);
		}
	}
	
	private class ExportDownloadLink extends DownloadLink {

		public ExportDownloadLink(String id, File file) {
			super(id, file);
			// TODO Auto-generated constructor stub
		}

		
		@Override
		public void onClick() {
			
			try {
			
			final File file = new WordListExport(wordList).getFile();
			 
			if (file == null)
			{
				throw new IllegalStateException(getClass().getName() +
					" failed to retrieve a File object from model");
			}
			final String fn = file.getName();


			IResourceStream resourceStream = new FileResourceStream(new org.apache.wicket.util.file.File(file));
			getRequestCycle().setRequestTarget(new ResourceStreamRequestTarget(resourceStream)
			{
				@Override
				public String getFileName()
				{
					return fn;
				}

				@Override
				public void respond(RequestCycle requestCycle)
				{
					super.respond(requestCycle);
					file.delete();
					 
					
				}
			});
			
			}
			
			catch(Exception e) {
				e.printStackTrace();
			}
		}
		
	}

}